<?php
/**
 * City
 * Класс City отвечает за обработку городов (поддоменов)
 * @author Sayp
 */
class City extends ActiveRecord {
	protected static $_tableName = 'city';
	protected static $_pkName = 'ID_city';
	
	protected static $_essenceType = 1;
	
	/**
	 * @var City
	 */
	private static $objCity = null;
	
	/**
	 * Получаем объект города по поддомену
	 * @return City
	 */
	public static function getCity() {
		if (self::$objCity) return self::$objCity;
		
		$sub = self::getSub();
		
		self::$objCity = new City();
		self::$objCity->find('first', array('conditions' => "`city_url` = '" . $sub . "'"));
		
		return self::$objCity;
	}
	
	/**
	 * Возвращаем поддомен
	 */
	public static function getSub() {
		$siteUrl = $_SERVER['SERVER_NAME'];
		if (strpos($siteUrl, SITE)) return substr($siteUrl, 0, strpos($siteUrl, SITE) - 1);
		
		return '';
	}
	
	/**
	 * Формируем список городов для селекта
	 */
	public static function getCitiesForSelect() {
		$objCity = new City();
		
		$arrCities = $objCity->find('all', array(
			'select' => '`ID_city`, `city_name`',
			'order' => '`city_name` ASC'
		));

        return Service_ArrayConverter::makeSimpleArrayToSelect($arrCities, 'ID_city', 'city_name');
	}
	
	protected function afterValidation() {
		$objDB = Service_Database::instance();
		$stmt = "SELECT `ID_city` FROM `city` WHERE `city_url` = '" . $this->getField('city_url') . "'";
		if ($this->id) $stmt .= ' AND `ID_city` != ' . $this->id;
		if ($objDB->isRecordExist($stmt)) $this->arrErrors = 'Такой url уже используется';
	}
}